package com.cheer.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cheer.service.TencentMapService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
@Slf4j
public class TencentMapServiceImpl implements TencentMapService {

    @Value("${tencentMap.key}")
    private String KEY;

    @Autowired
    private RestTemplate restTemplate;
 
    /**
     * 计算腾讯地图距离
     * @param max 终点个数
     * @param from 起点坐标，格式：lat,lng;lat,lng...
     * （经度与纬度用英文逗号分隔，坐标间用英文分号分隔）
     * @param to 终点(可以传入多个终点坐标，格式：lat,lng;lat,lng...
     * （http://apis.map.qq.com/ws/distance/v1/matrix?mode=walking&from=22.53332,113.93041&to=22.529565,113.946620&key=NNWBZ-VJ4CX-PON4E-TQHCA-ZY5Q7-Z7BE7
     * {"status":0,"message":"query ok","request_id":"6801723632908333780","result":{"rows":[{"elements":[{"distance":2496}]}]}}
     * @return 距离 米
     */
    public Double[] getLocation(int max, String from, String to) {
        Double[] distances = new Double[max];
        //请求路径
        String getURL = "http://apis.map.qq.com/ws/distance/v1/matrix";
        //计算方式：driving（驾车）、walking（步行）默认：driving
        String mode = "walking";
        String urlString = getURL + "?mode=" + mode + "&from=" + from + "&to=" + to + "&key=" + KEY;
        String result = "";
        try {
            log.info("纬度信息："+urlString);
            result = restTemplate.getForObject(urlString, String.class);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        if (!result.contains("result")) {
            log.error("调用腾讯地图计算步行距离返回报错，{}", result);
            return distances;
        }
        log.info("调用腾讯地图计算步行距离返回结果：{}", result);
        // 转JSON格式
        JSONObject jsonObject = JSON.parseObject(result).getJSONObject("result");
        //elements是[](数组格式)所以使用JSONArray获取
        JSONArray rows = jsonObject.getJSONArray("rows");
        // 1对多模式
        JSONArray adInfo = rows.getJSONObject(0).getJSONArray("elements");
        //for数组
        for (int j = 0; j < adInfo.size(); j++) {
            JSONObject jsonObject2 = adInfo.getJSONObject(j);
            //获取距离(获取到的是m为单位)
            String distance = jsonObject2.getString("distance");
            double distanceD = Double.parseDouble(distance);
            distances[j] = distanceD;
        }
        return distances;
    }

    @Override
    public Double getLocation(String from, String to) {
        Double[] location = getLocation(1, from, to);
        return location[0];
    }
}